package com.landian.demo.distributedlock.springboot.service.impl;

import com.landian.demo.distributedlock.springboot.db.ProductDB;
import com.landian.demo.distributedlock.springboot.enums.ResultEnum;
import com.landian.demo.distributedlock.springboot.exception.MyException;
import com.landian.demo.distributedlock.springboot.service.OrderService;
import com.landian.demo.distributedlock.springboot.service.RedisLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.Random;

/**
 *
 * @author caojl
 **/
@Service
@Slf4j
public class OrderServiceImpl implements OrderService{

    @Autowired
    private RedisLock redisLock;

    /**
     * 超时时间 10s
     */
    private static final int TIMEOUT = 10 * 1000;

    @Override
    public void secondKill(String productId) {
        String threadName = Thread.currentThread().getName();
        // 加锁
        long time = System.currentTimeMillis() + TIMEOUT;
        if(!redisLock.lock(productId, String.valueOf(time))){
            throw new MyException(101,
                    MessageFormat.format("哎哟喂， 人也太多了，[{0}]换个姿势再试试～～",
                            threadName));
        }
        long stock = ProductDB.getStock(productId);
        if(stock <= 0){
//            throw new MyException(ResultEnum.OUT_STOCK);
            throw new MyException(102,
                    MessageFormat.format("哎哟喂， [{0}]你慢了一步，商品抢购完了，活动已经结束～～",
                            threadName));
        }
        ProductDB.decreaseStock(productId);
        log.error("线程[{}]抢到了商品[{}]的第[{}]个", threadName, productId, stock);
        try {
            Random random = new Random();
            long sleepTime = random.nextInt(100);
            Thread.sleep(sleepTime);
        } catch (InterruptedException e) {
            log.error(e.getMessage(), e);
        }
        // 解锁
        redisLock.unlock(productId, String.valueOf(time));
    }
}
